import { Form, Button, Col, Row, Input, Select, DatePicker, Table, InputNumber, message } from 'antd';
import React, { useContext, useState, useEffect, useRef, Component } from 'react';
import moment from 'moment';
import { Quotationdetail, Quotationlist, Orderadd } from '../../../services/auth';
import { getToken } from '../../../utils/auth';

const EditableContext = React.createContext(null);

// editableTable中的行组件
const EditableRow = ({ index, ...props }) => {
	const [ form ] = Form.useForm();
	return (
		<Form form={form} component={false}>
			<EditableContext.Provider value={form}>
				<tr {...props} />
			</EditableContext.Provider>
		</Form>
	);
};

// editableTable中的列组件
const EditableCell = ({ title, editable, children, dataIndex, record, handleSave, ...restProps }) => {
	const [ editing, setEditing ] = useState(false);
	const inputRef = useRef(null);
	const form = useContext(EditableContext);
	useEffect(
		() => {
			if (editing) {
				inputRef.current.focus();
			}
		},
		[ editing ]
	);

	const toggleEdit = () => {
		setEditing(!editing);
		form.setFieldsValue({
			[dataIndex]: record[dataIndex]
		});
	};

	const save = async () => {
		try {
			const values = await form.validateFields();
			toggleEdit();
			handleSave({ ...record, ...values });
		} catch (errInfo) {
			console.log('Save failed:', errInfo);
		}
	};

	let childNode = children;

	if (editable) {
		childNode = editing ? (
			<Form.Item
				style={{
					margin: 0
				}}
				name={dataIndex}
				rules={[
					{
						required: true,
						message: `不能为空`
					}
				]}
				initialValue={100}
			>
				<InputNumber
					min={0}
					max={100}
					formatter={(value) => `${value}%`}
					parser={(value) => value.replace('%', '')}
					ref={inputRef}
					onPressEnter={save}
					onBlur={save}
				/>
			</Form.Item>
		) : (
			<div
				className="editable-cell-value-wrap"
				style={{
					paddingRight: 24
				}}
				onClick={toggleEdit}
			>
				{children}%
			</div>
		);
	}

	return <td {...restProps}>{childNode}</td>;
};

// form中的属性
const { Option } = Select;
const { RangePicker } = DatePicker;

export default class Quot_CreateOrder extends Component {
	constructor(props) {
		super(props);
		const { handleCreateClick } = this.props;
		this.handleCreateClick = handleCreateClick;
		// 父类的state
		this.state = {
			// 这个是商品数据
			dataSource: [],
			// 这个是可用于生成报价单的询价单列表
			quotationList: []
		};
		// editableTable的列
		this.columns = [
			{
				title: '产品编号',
				dataIndex: 'goods_id'
			},
			{
				title: '产品名称',
				dataIndex: 'goods_name'
			},
			{
				title: '订货数量',
				dataIndex: 'quantity'
			},
			{
				title: '产品定价',
				dataIndex: 'price'
			},
			{
				title: '折扣（可编辑）',
				dataIndex: 'discount',
				width: '15%',
				editable: true
			},
			{
				title: '产品价格',
				dataIndex: 'current_price'
			}
		];
		this.user = JSON.parse(getToken());
	}
	formRef = React.createRef();
	// 获得询价单列表
	componentDidMount() {
		Quotationlist().then(
			(response) => {
				//拿到我们想要渲染的数据(res)
				this.setState({
					quotationList: response.data
				});
			},
			(error) => {
				console.log('失败了', error);
			}
		);
	}
	// 选项改变就触发下面这个函数
	onSelectChange = (value) => {
		if (value) {
			Quotationdetail(value).then(
				(response) => {
					console.log(response.data);
					//拿到我们想要渲染的数据(res)
					this.setState({
						dataSource: [
							...response.data.goods,
							{
								key: response.data.goods.length,
								goods_id: '总计',
								discount: response.data.discount,
								current_price: response.data.total_price
							}
						]
					});
					this.formRef.current.setFieldsValue({
						company: response.data.company_id + ' ' + response.data.company_name,
						req_deliv_date: moment(response.data.req_deliv_date, 'YYYY-MM-DD'),
						ship_to_address: response.data.ship_to_address
					});
				},
				(error) => {
					console.log('失败了', error);
				}
			);
		} else {
			this.formRef.current.resetFields();
			this.setState({ dataSource: [] });
		}
	};
	// 点击提交后触发的事件
	onFinish = (values) => {
		// Orderadd({
		// 	goods: this.state.dataSource,
		// 	discount: this.state.dataSource[this.state.dataSource.length - 1].discount,
		// 	total_price: this.state.dataSource[this.state.dataSource.length - 1].current_price,
		// 	company: values.company,
		// 	inquiry_id: values.inq_id,
		// 	operator_id: this.user.id,
		// 	req_deliv_date: values.req_deliv_date.format('YYYY-MM-DD'),
		// 	ship_to_address: values.ship_to_address,
		// 	valid_from: values.valid[0].format('YYYY-MM-DD'),
		// 	valid_to: values.valid[1].format('YYYY-MM-DD')
		// }).then(
		// 	(response) => {
		// 		if (response.data.result === 'success') {
		// 			message.success('报价单' + response.data.Order_id + '已创建成功');
		// 			this.formRef.current.resetFields();
		// 			this.handleCreateClick();
		// 		} else {
		// 			message.info('提交失败，请重试');
		// 		}
		// 	},
		// 	(error) => {
		// 		console.log('数据获取失败', error);
		// 	}
		// );
		console.log(values);
	};
	onReset = () => {
		this.formRef.current.resetFields();
		this.setState({ dataSource: [] });
	};
	// 用于editableTable的函数
	handleSave = (row) => {
		const newData = [ ...this.state.dataSource ];
		const index = newData.findIndex((item) => row.key === item.key);
		const item = newData[index];
		newData.splice(index, 1, { ...item, ...row, current_price: row.discount * row.price / 100 });
		let sum = 0;
		for (let j = 0, len = newData.length; j < len; j++) {
			if (newData[j].quantity && newData[j].current_price) {
				sum += newData[j].quantity * newData[j].current_price;
			}
		}
		if (row.key != newData.length - 1) {
			newData.splice(newData.length - 1, 1, {
				key: newData.length - 1,
				goods_id: '总计',
				price: sum,
				current_price: sum
			});
		}
		this.setState({
			dataSource: newData
		});
	};

	render() {
		// 拿到editableTable的属性
		const { dataSource } = this.state;
		const components = {
			body: {
				row: EditableRow,
				cell: EditableCell
			}
		};
		const columns = this.columns.map((col) => {
			if (!col.editable) {
				return col;
			}

			return {
				...col,
				onCell: (record) => ({
					record,
					editable: col.editable,
					dataIndex: col.dataIndex,
					title: col.title,
					handleSave: this.handleSave
				})
			};
		});
		return (
			<Form layout="vertical" hideRequiredMark onFinish={this.onFinish} ref={this.formRef}>
				<Row gutter={24}>
					<Col span={12}>
						<Form.Item name="quotation_id" label="报价单编号" rules={[ { required: true, message: '请选择询价单' } ]}>
							<Select placeholder="请选择报价单" onChange={this.onSelectChange} allowClear>
								{this.state.quotationList.map((quotation) => (
									<Option value={quotation.id} key={quotation.id}>
										{quotation.id}
									</Option>
								))}
							</Select>
						</Form.Item>
					</Col>
					<Col span={12}>
						<Form.Item name="company" label="公司">
							<Input disabled />
						</Form.Item>
					</Col>
				</Row>
				<Row gutter={24}>
					<Col span={8}>
						<Form.Item name="valid" label="生效期限" rules={[ { required: true, message: '请填写生效期限' } ]}>
							<RangePicker />
						</Form.Item>
					</Col>
					<Col span={4}>
						<Form.Item name="req_deliv_date" label="预计送达日期">
							<DatePicker disabled />
						</Form.Item>
					</Col>
					<Col span={12}>
						<Form.Item name="ship_to_address" label="送货地点">
							<Input disabled />
						</Form.Item>
					</Col>
				</Row>
				<Row gutter={24} />
				{/* editableTable */}
				<Table
					components={components}
					rowClassName={() => 'editable-row'}
					bordered
					dataSource={dataSource}
					columns={columns}
					pagination={false}
				/>

				<Form.Item>
					<div
						style={{
							textAlign: 'right'
						}}
					>
						<Button htmlType="reset" style={{ marginRight: 8 }}>
							重置
						</Button>
						<Button type="primary" htmlType="submit">
							保存
						</Button>
					</div>
				</Form.Item>
			</Form>
		);
	}
}
